$(function() {

    let keyArr = [];

    $("#search-btn").on("tap", function() {
        let keyword = $(this).siblings("input").val().trim();
        if (keyword) {
            keyArr.push(keyword);
            localStorage.setItem("keyArr", JSON.stringify(keyArr));
            location.href = "search-result.html?keyword=" + keyword;
        } else {
            mui.toast("请你输入商品名称");
            $("#search-in").val("");
        }
    })

    $("body").on("tap", "#history-top li", function() {
        let str = ($(this).text()).toString();
        str = str.replace(/\s+/g, "")
        $("#search-in").val(str);

    });



    if (localStorage.getItem("keyArr")) {
        keyArr = JSON.parse(localStorage.getItem("keyArr"));
        let html = template("historyTpl", { result: keyArr });
        $("#history-top").html(html)

    }
    $("body").on("tap", ".mui-icon-closeempty ", function() {
        console.log("按下删除按钮");
        console.log("$(this).parent().attr('data-ke'y')" + $(this).parent().attr("data-key"));
        removeSearchData($(this).parent().attr("data-key"));
    });
    $(".clear").on("tap", function() {
        localStorage.removeItem("keyArr");
        location.reload();
    })
})

let removeSearchData = function(key) {
    let list = JSON.parse(localStorage.getItem("keyArr"));
    console.log("key" + key);
    console.log("list" + list);
    $.each(list, function(i, item) {
        if (key == item) {
            list.splice(i, 1);
            console.log("找到相应的key");
        }
    });
    localStorage.setItem("keyArr", JSON.stringify(list));
    keyArr = JSON.parse(localStorage.getItem("keyArr"));
    let html = template("historyTpl", { result: keyArr });
    $("#history-top").html(html);
    location.reload();
}